import appConfig from "@/config/index.js";
import LuchRequest from '@/plugins/luch-request/index.js';
import systemUtils from "@/utils/system/index.js";
import logUtils from "@/utils/log/index.js";
import uniUtils from "@/utils/uni/index.js";
import config from "@/config/index.js";
import cryptoJS from "crypto-js"
import debug from './debug'

const service = new LuchRequest({
	baseURL: appConfig.baseURL,
	timeout: 120000
})

class Lock {
	
	constructor() {
		this.flag = false;
		this.data = {};
		this.lockArr = []
	}

	wait() { // 等待锁
		let that_ = this
		let pro = new Promise(resolve => {
			if (this.flag) {
				resolve(this.data);
			} else {
				that_.lockArr.push(resolve)
			}
		});
		return pro
	}

	notify(data = {}) {
		this.data = data;
		this.flag = true;
		for (let i = 0; i < this.lockArr.length; i++) {
			this.lockArr[i](this.data)
		}
		this.lockArr = []
	}
}
function objKeySort(arys) { 
  //先用Object内置类的keys方法获取要排序对象的属性名，再利用Array原型上的sort方法对获取的属性名进行排序，newkey是一个数组
  var newkey = Object.keys(arys).sort();　　 
  //console.log('newkey='+newkey);
  var newObj = {}; //创建一个新的对象，用于存放排好序的键值对
  for(let i = 0; i < newkey.length; i++) {
      //遍历newkey数组
      newObj[newkey[i]] = arys[newkey[i]]; 
      //向新创建的对象中按照排好的顺序依次增加键值对
  }
  return newObj; //返回排好序的新对象
}

var loginHandle = false
const lock = new Lock()
function isObject(value) {
  return typeof value === 'object' && value !== null;
}

function isArray(obj) {
  return typeof obj === "object" && Array.isArray(obj);
}
// 请求拦截
service.interceptors.request.use(
	async (request) => {
		if(request.custom.authentication){
      if(!uni.getStorageSync("tenantId")){
      	request.abort();
      }
			// if(!uni.getStorageSync("hospitalId")){
			// 	request.abort();
			// }
			let userinfo = uni.getStorageSync('system-userinfo');
			if (!userinfo) {
				if (loginHandle) {
					await lock.wait();
				}
				if (!uni.getStorageSync('system-userinfo')) {
					loginHandle = true
					await systemUtils.login()
					loginHandle = false
				}
				lock.notify()
				userinfo = uni.getStorageSync('system-userinfo');
			} else {
				let nowTime = new Date().getTime();
				if ((userinfo.expiresTime - nowTime) < 300000) {
					if (await systemUtils.login()) {
						userinfo = uni.getStorageSync('system-userinfo');
					}
				}
			}
			try{
				console.log(request.data)
				if(request.data){
					let tmpKeys = Object.keys(request.data)
					for (var i = 0; i < tmpKeys.length; i++) {
						if (typeof request.data[tmpKeys[i]] === 'undefined') {
						  delete request.data[tmpKeys[i]]
						}
					}
					let arr = objKeySort(request.data)
					let keys = Object.keys(request.data)
					keys.sort()
					
					let signStr = ""
					for (let i = 0; i < keys.length; i++) {
						if(i != 0){
							signStr += "&"
						}
						
						let value = request.data[keys[i]]
						if(isObject(request.data[keys[i]])){
							value = JSON.stringify(request.data[keys[i]])
						}
						if(isArray(request.data[keys[i]])){
							if(request.data[keys[i]].length > 0){
								value = JSON.stringify(request.data[keys[i]])
							}else{
								value = ""
							}
						}
						signStr += `${keys[i]}=${value}`
					}
					signStr += ("&key="+appConfig.requestKey)
					
					console.log(keys,"加密字符串数组key")
					console.log(signStr,"加密字符串")
					// console.log(cryptoJS)
					console.log(cryptoJS.MD5(signStr).toString())
					
					request.header['sign-str'] = cryptoJS.MD5(signStr).toString()
				}
				
			}catch(e){
				console.log(e)
			}
			
			request.header = {
				...request.header,
        "tenant-id": uni.getStorageSync("tenantId"),
				// "hospital-id": uni.getStorageSync("hospitalId"),
				"Authorization": "Bearer " + userinfo.accessToken
			}
		}
		return request
	},
	err => {
		console.log(err)
		lock.notify();
		// logUtils.error(err);
		return Promise.reject(err);
	}
)

// 响应拦截
service.interceptors.response.use(
	(response) => {
		let config = response.config
		// console.log(response)
		// logUtils.request(response);
		if (response.statusCode === 200) {
			if (response.data.code === 0) {
				debug.success(response.config.custom?.title, response.config.baseURL +response.config.url, response.data)
				return response.data.data;
			}else if(response.data.code == 401){
				uni.removeStorageSync('system-userinfo');
				return service(config)
			}else if(response.data.code === 1104001001){
				debug.fail(response.config.custom?.title, response.config.baseURL +response.config.url, response.data)
				return Promise.reject(response.data);
			}else {
				uni.showModal({
					title:'提示',
					content:response.data.msg,
					showCancel:false
				})
				debug.fail(response.config.custom?.title, response.config.baseURL +response.config.url, response.data)
				return Promise.reject(response.data.msg);
			}
		} else {
			console.log('sss',response)
			uniUtils.toast("服务忙！");
			debug.fail(response.config.custom?.title, response.config.baseURL +response.config.url, response.data)
			return Promise.reject(response.data.msg);
		}
	},(error) => {
		// console.log(error)
		// logUtils.request(error);
		if(error.toString() !== "TypeError: t.abort is not a function"){
			console.log('eee',error)
			uniUtils.toast("服务忙！");
		}
		// debug.fail(error.config?.custom?.title, error.config.baseURL + error.config.url, error.data)
		return Promise.reject(error.statusCode);
	}
);

export default service;
